<template>
  <div class="app-container" v-loading="pushLoading" element-loading-text="消息推送中">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入产品名称" clearable size="small"/>
          </el-form-item>

          <el-form-item label="状态" prop="status" v-if="false">
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['content:systemPush:query']"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['content:systemPush:add']"
            >新增
            </el-button>
            <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['content:systemPush:export']"
                       @click="handleExport"
            >导出
            </el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="contentPushList" border>
          <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true"/>
          <el-table-column label="内容" align="center" prop="content" :show-overflow-tooltip="true"/>
          <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handlePush(scope.row)"
                v-hasPermi="['content:systemPush:push']"
              >推送
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['content:systemPush:remove']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['content:systemPush:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改内容通知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属组织" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true"
                      placeholder="请选择归属组织"
          />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="form.content" :rows="4" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="pushOpen" width="800px" append-to-body>
      <div style="font-weight: bold;font-size: 16px;color: black;margin-bottom: 30px">推送内容</div>
      <el-form ref="pushFormContent" :model="pushForm" label-width="80px">
        <el-form-item label="标题" prop="deptId">
          {{ pushForm.title }}
        </el-form-item>

        <el-form-item label="内容" prop="deptId">
          {{ pushForm.content }}
        </el-form-item>

        <el-form-item label="所属组织" prop="deptId">
          <treeselect v-model="pushForm.deptId" :options="deptOptions" :show-count="true"
                      placeholder="请选择归属组织" @input="selectDeptChanged"
                      v-if="false"
          />
          {{ pushForm.deptName }}
        </el-form-item>
      </el-form>

      <el-divider/>

      <div style="font-weight: bold;font-size: 16px;color: black;margin-bottom: 30px">推送目标</div>
      <el-form ref="pushFormTarget" :model="pushForm" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机类型" prop="sourceType">
              <el-select
                v-model="pushForm.sourceType"
                placeholder="手机类型"
                @change="handleChangeSourceType"
              >
                <el-option
                  v-for="item in sourceTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="pushForm.gender"
                placeholder="性别"
                @change="handleChangeGender"
              >
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="推送区域">
              <el-cascader :options="regions" v-model="selectedRegions" @change="handleChangeRegion"
                           filterable placeholder="区域"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="目标人数">
              <span>{{ targetAppUserPushCount }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="推送时间" prop="resource">
              <el-radio-group aria-checked="true" v-model="pushForm.delayTime">
                <el-radio label="0">现在</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form ref="pushForm" :model="pushForm" label-width="80px" v-if="false">
        <el-form-item label="标题" prop="deptId">
          {{ pushForm.title }}
        </el-form-item>

        <el-form-item label="内容" prop="deptId">
          {{ pushForm.content }}
        </el-form-item>

        <el-form-item label="所属组织" prop="deptId">
          <treeselect v-model="pushForm.deptId" :options="deptOptions" :show-count="true"
                      placeholder="请选择归属组织" @input="selectDeptChanged"
                      v-if="false"
          />
          {{ pushForm.deptName }}
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机类型" prop="sourceType">
              <el-select
                v-model="pushForm.sourceType"
                placeholder="手机类型"
                @change="handleChangeSourceType"
              >
                <el-option
                  v-for="item in sourceTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="pushForm.gender"
                placeholder="性别"
                @change="handleChangeGender"
              >
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="推送区域">
              <el-cascader :options="regions" v-model="selectedRegions" @change="handleChangeRegion"
                           filterable placeholder="区域"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="目标人数">
              <span>{{ targetAppUserPushCount }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="推送时间" prop="resource">
              <el-radio-group aria-checked="true" v-model="pushForm.delayTime">
                <el-radio label="0">现在</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="clickPushSubmit" :disabled="targetAppUserPushCount===0">开 始</el-button>
        <el-button @click="cancelPush">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptTreeSelect } from '@/api/system/dept'
import {
  addContentPush,
  delContentPush,
  exportContentPush,
  jpushToSomeUser,
  listContentPush,
  updateContentPush
} from '@/api/system/contentPush'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { CodeToText, provinceAndCityDataPlus } from 'element-china-area-data'
import { conditionAppUserCount } from '@/api/system/user'

export default {
  name: 'index',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 数据
      contentPushList: [],
      // 状态数据字典
      statusOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 推送弹出层标题
      pushTitle: '',
      // 是否显示推送弹出层
      pushOpen: false,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 当前选择的组织
      selectedOrgCode: '',
      form: {},
      pushForm: {
        title: undefined,
        content: undefined,
        deptId: undefined,
        deptName: undefined,
        position: undefined,
        delayTime: '0',
        sourceType: 'all',
        gender: 'all'
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {},
      // 中国省、市
      regions: provinceAndCityDataPlus,
      // 选择的区域
      selectedRegions: [''],
      // 推送用户的数量
      targetAppUserPushCount: 0,
      // 消息推送中
      pushLoading: false,

      // 手机类型数据
      sourceTypeOptions: [{ value: 'all', label: '全部' }, { value: '1', label: 'IOS' }, { value: '2', label: '安卓' }],
      // 性别数据
      genderOptions: [{ value: 'all', label: '全部' }, { value: '0', label: '男' }, {
        value: '1',
        label: '女'
      }, { value: '2', label: '未知' }]
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    /** 查询内容通知列表 */
    getList() {
      this.loading = true
      if (!this.queryParams.deptId) {
        // 取出当前用户的组织ID
        this.queryParams.deptId = this.$store.getters.deptId
      }
      listContentPush(this.queryParams).then(response => {
        this.contentPushList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.selectedOrgCode = data.id
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 查询需推送用户的数量
    getTargetUserPushCount() {
      conditionAppUserCount({
        deptId: this.pushForm.deptId,
        position: this.pushForm.position,
        sourceType: this.pushForm.sourceType,
        gender: this.pushForm.gender
      }).then(response => {
        if (response.code === 200) {
          this.targetAppUserPushCount = response.data
        } else {
          this.targetAppUserPushCount = 0
        }
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        content: undefined,
        deptId: undefined,
        status: '0'
      }
      this.resetForm('form')
    },

    /** 新增按钮操作 */
    handleAdd() {
      if (this.selectedOrgCode === '') {
        this.selectedOrgCode = null
      }

      this.reset()
      this.form.deptId = this.selectedOrgCode
      this.open = true
      this.title = '添加内容通知'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = JSON.parse(JSON.stringify(row))

      this.open = true
      this.title = '修改内容通知'
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delContentPush({ id: row.id })
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateContentPush(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addContentPush(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },

    /** 推送按钮操作 */
    handlePush(row) {
      this.pushForm.sourceType = 'all'
      this.pushForm.gender = 'all'
      this.pushForm.title = row.title
      this.pushForm.content = row.content
      this.pushForm.deptId = row.deptId
      this.pushForm.deptName = row.deptName
      this.getTargetUserPushCount()
      this.pushOpen = true
      this.pushTitle = '系统推送'
    },

    /**
     * 推送时所选组织发生改变
     */
    selectDeptChanged(deptId) {
      this.getTargetUserPushCount()
    },

    /**
     * 选择区域发生变化
     * @param selectedRegion
     */
    handleChangeRegion(selectedRegion) {
      console.log(selectedRegion)
      let province = CodeToText[selectedRegion[0]]
      let city = CodeToText[selectedRegion[1]]
      if (province) {
        if (province === '全部') {
          province = ''
        }
        if (city === '市辖区' || city === '全部' || city === undefined) {
          city = ''
        }
        this.pushForm.position = province + city
      } else {
        this.pushForm.position = null
      }

      this.getTargetUserPushCount()
    },

    // 改变手机类型时
    handleChangeSourceType() {
      this.getTargetUserPushCount()
    },

    // 改变性别时
    handleChangeGender() {
      this.getTargetUserPushCount()
    },

    /**
     * 取消推送
     */
    cancelPush() {
      this.pushOpen = false
    },

    /**
     * 点击提交推送
     */
    clickPushSubmit() {
      this.$confirm('是否推送消息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pushOpen = false
        this.pushLoading = true
        jpushToSomeUser(this.pushForm).then(response => {
          // 隐藏加载
          this.pushLoading = false
          if (response.code === 200) {
            this.msgSuccess('推送完成, 已推送' + response.data + '条')
          }
        }, () => {
          // 隐藏加载
          this.pushLoading = false
        })
      })
    },

    /**
     * 确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportContentPush(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>

<style scoped>
.el-row {
  display: flex;
  flex-wrap: wrap;
}

</style>
